#include "cpu.h"
#include "typedef.h"
#include "eeprom_driver.h"





static void flash_clear_flag(void)
{
	FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP|FLASH_FLAG_PGERR |FLASH_FLAG_WRPRTERR);
}

void eeporm_init(void)
{
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_CRC, ENABLE);
}

void eeprom_read(u32 Page_Address, u8 *pbuf )
{
	for(int i=0; i<EEPROM_PAGE_SIZE; i++)
		pbuf[i] = *(volatile u8 * )(Page_Address+EEPROM_ADDRESS+i);
}

//Erase 1 page = 256 bytes
//该函数尽可能少的调用，因为会关中断，擦除时间 16ms
void eeprom_erase(u32 Page_Address)
{
	__disable_irq();//关中断，
	FLASH_Unlock_Fast();
	flash_clear_flag();
	FLASH_ErasePage_Fast( Page_Address + EEPROM_ADDRESS );
	FLASH_Lock_Fast();
	//SysTick_compensation(16);
	__enable_irq();
}
//该函数尽可能少的调用，因为会关中断，写时间 2ms
void eeprom_write(u32 Page_Address, void *pbuf)
{
	__disable_irq();
	FLASH_Unlock_Fast();
	flash_clear_flag();
	FLASH_ProgramPage_Fast( Page_Address + EEPROM_ADDRESS, (u32*)pbuf );
	FLASH_Lock_Fast();
	__enable_irq();
}
u8 eeprom_page_erase_ok(u32 Page_Address)
{
	u16 * p = (u16 *)(EEPROM_ADDRESS+Page_Address);
	for(int i=0; i<(EEPROM_PAGE_SIZE>>1); i++)
	{
		if(ERASE_FLASH_VALUE != *p)
			return 0;
		p++;
	}
	return 1;
}
void eeprom_page_buff_pading(u8 * addr)
{
	u16 * p = (u16 *)(addr);
	for(int i=0; i<(EEPROM_PAGE_SIZE>>1); i++)
		p[i]=ERASE_FLASH_VALUE;
}

u32 eeprom_crc_calcblock(u32 buff[], u32 lenght)
{
	CRC_ResetDR();
	return CRC_CalcBlockCRC(buff,lenght);
}
